package com.lulu.project.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lulu.common.model.entity.InterfaceInfo;
import com.lulu.common.model.entity.User;
import com.lulu.sdk.client.LuluClient;
import com.lulu.project.annotation.AuthCheck;
import com.lulu.project.common.*;
import com.lulu.project.constant.CommonConstant;
import com.lulu.project.exception.BusinessException;
import com.lulu.project.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.lulu.project.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import com.lulu.project.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.lulu.project.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import com.lulu.project.model.enums.InterfaceInfoStatusEnum;
import com.lulu.project.model.enums.MethodEnum;
import com.lulu.project.service.InterfaceInfoService;
import com.lulu.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 接口管理
 *
 * @author lulu
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;


    @GetMapping("/refresh")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<String> refresh(){
        String s = HttpUtil.get("http://localhost:8090/route/refresh");
        return ResultUtils.success(s);
    }

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                            HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String content = interfaceInfoQuery.getDescription();
        // content 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }


    @Value("${api.gateway.address}")
    private String addr;

    /**
     * 发布
     *
     * @param idRequest
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {

        if(idRequest==null||idRequest.getId()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        InterfaceInfo byId = interfaceInfoService.getById(idRequest.getId());
        if(byId==null||byId.getStatus()==null||byId.getId()==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String accessSecret = loginUser.getAccessSecret();
        LuluClient client = new LuluClient(accessKey, accessSecret);

        String method = byId.getMethod();
        if(method==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 测试接口是否可以调用
        String result = null;
        String uri = addr + byId.getUrl();
        String requestParams = byId.getRequestParams();
        if(requestParams==null||byId.getUrl()==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(MethodEnum.POST.getValue().equals(method)){
            result=client.postWithJson(uri, requestParams);
        }else if(MethodEnum.GET.getValue().equals(method)){
            Map<String, Object> map = JSONUtil.parseObj(requestParams).toBean(Map.class);
            result = client.getWithAccess(uri, map);
        }

        log.info(byId.getUrl()+"接口返回:"+result);
        if(StringUtils.isBlank(result)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        if(!Objects.equals(byId.getStatus(), InterfaceInfoStatusEnum.OFFLINE.getStatus())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        UpdateWrapper<InterfaceInfo> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",byId.getId()).set("status",InterfaceInfoStatusEnum.ONLINE.getStatus());
        boolean update = interfaceInfoService.update(updateWrapper);

        // 刷新网关路由
        refresh();
        return ResultUtils.success(update);
    }
    /**
     * 下线
     *
     * @param idRequest
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest) {
        if(idRequest==null||idRequest.getId()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        InterfaceInfo byId = interfaceInfoService.getById(idRequest.getId());
        if(byId==null||byId.getStatus()==null||byId.getId()==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        if(!Objects.equals(byId.getStatus(), InterfaceInfoStatusEnum.ONLINE.getStatus())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        UpdateWrapper<InterfaceInfo> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",byId.getId()).set("status",InterfaceInfoStatusEnum.OFFLINE.getStatus());
        boolean update = interfaceInfoService.update(updateWrapper);

        // 刷新网关路由
        refresh();

        return ResultUtils.success(update);
    }


    @PostMapping("/invoke")
    public BaseResponse<Object> invoke(@RequestBody InterfaceInfoInvokeRequest invokeRequest,
                                       HttpServletRequest request){

        if(invokeRequest==null|| invokeRequest.getId() <=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long id = invokeRequest.getId();
        String requestBody = invokeRequest.getUserRequestParams();

        InterfaceInfo byId = interfaceInfoService.getById(id);
        if(byId==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        if(!byId.getStatus().equals(InterfaceInfoStatusEnum.ONLINE.getStatus())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口已下线");
        }

        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String accessSecret = loginUser.getAccessSecret();
        LuluClient client = new LuluClient(accessKey, accessSecret);

        String method = byId.getMethod();
        if(method==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 测试接口是否可以调用
        String result = null;
        String uri = addr + byId.getUrl();
        if(MethodEnum.POST.getValue().equals(method)){
            result=client.postWithJson(uri, requestBody);
        }else if(MethodEnum.GET.getValue().equals(method)){
            Map<String, Object> map = JSONUtil.parseObj(requestBody).toBean(Map.class);
            result = client.getWithAccess(uri, map);
        }

        return ResultUtils.success(result);
    }

}
